package books4africa

import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUser
import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserDetailsService
import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.authority.GrantedAuthorityImpl
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UsernameNotFoundException

class CustomUserDetailsService implements GrailsUserDetailsService {

	static final List NO_ROLES = [new GrantedAuthorityImpl(SpringSecurityUtils.NO_ROLE)]


	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		return loadByUsername(username)
	}

	@Override
	public UserDetails loadUserByUsername(String username, boolean loadRoles)
			throws UsernameNotFoundException, DataAccessException {
		User.withTransaction { status ->
			User user = User.findByUsername(username)
			
			if (!user) throw new UsernameNotFoundException("User Not Found", username)
			
			def authorities = user.authorities.collect {
				new GrantedAuthorityImpl(it.authority)
				
			}
			
			return new User(
				user.username, 
				user.password, 
				user.enabled, 
				!user.accountExpired, 
				!user.passwordExpired, 
				!user.accountLocked, 
				authorities ?: NO_ROLES, 
				user.id
			)
		}
	}	
	
  
}
